package com.crb.crm.manage.oos;

import com.crb.crm.manage.enums.OssType;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * Package: com.crb.crm.manage.oos
 * Description：
 * Author: huangjian
 * Date:  2020/9/10 14:47
 * Modified By:
 *
 * @author huangjian
 */
@Component
public class OSSUtilCtx {
    @Resource
    private List<OSSUtil> ossUtilList;

    @Value("${app.oss.type}")
    private String ossTypeCode;

    private OSSUtil chooseOne() {
        OssType ossType = OssType.valueOf(ossTypeCode);
        if (Objects.isNull(ossType)) {
            throw new IllegalArgumentException("系统存储配置出错，请检查");
        }
        Optional<OSSUtil> first = ossUtilList.stream().filter(item -> ossType.equals(item.support())).findFirst();
        if (first.isPresent()) {
            return first.get();
        }
        throw new IllegalArgumentException("oss渠道不支持");
    }

    private OSSUtil chooseOne(OssType ossType) {
        Optional<OSSUtil> first = ossUtilList.stream().filter(item -> ossType.equals(item.support())).findFirst();
        if (first.isPresent()) {
            return first.get();
        }
        throw new IllegalArgumentException("oss渠道不支持");
    }

    public OssType getOssType() {
        return OssType.valueOf(ossTypeCode);
    }


    public  boolean upload(InputStream is, String key){
        return chooseOne().upload(is, key);
    }

    public boolean delete(String key){
        return chooseOne().delete( key);
    }

    public InputStream download(OssType ossType,String key) throws FileNotFoundException {
        return chooseOne(ossType).download(key);
    }
}
